package net.entelijan.cobean.examples.data.literature.wrapper;

import java.util.Date;

import javax.xml.datatype.XMLGregorianCalendar;

import org.dozer.CustomConverter;
import org.dozer.converters.ConversionException;
import org.springframework.util.ClassUtils;

public class WsDateConverter implements CustomConverter {

	public WsDateConverter() {
		super();
	}

	@Override
	public Object convert(Object existingDestinationFieldValue,
			Object sourceFieldValue, Class<?> destinationClass,
			Class<?> sourceClass) {
		Object re;
		try {
			if (sourceFieldValue == null) {
				re = null;
			} else {
				if (ClassUtils.isAssignable(Date.class, sourceClass)) {
					re = WsUtil
							.createXMLGregorianCalendar((Date) sourceFieldValue);
				} else if (ClassUtils.isAssignable(XMLGregorianCalendar.class,
						sourceClass)) {
					XMLGregorianCalendar xmlgc = (XMLGregorianCalendar) sourceFieldValue;
					re = xmlgc.toGregorianCalendar().getTime();
				} else {
					re = null;
				}
			}
		} catch (Exception e) {
			throw new ConversionException(e);
		}
		return re;
	}

}
